<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class ListNode {
      constructor(val, next = null) {
        this.val = val;
        this.next = next;
      }
    }

    class LinkedList {
      constructor() {
        this.head = null;
        this.tail = null;
        this.size = 0;
      }

      addAtHead(val) {
        let node = new ListNode(val, this.head);
        this.head = node;
        if (!this.tail) {
          this.tail = node;
        }
        this.size++;
      }

      addAtTail(val) {
        let node = new ListNode(val);
        if (!this.head) {
          this.head = node;
          this.tail = node;
        } else {
          this.tail.next = node;
          this.tail = node;
        }
        this.size++;
      }

      get(index) {
        if (index < 0 || index >= this.size) {
          return -1;
        }
        let node = this.head;
        for (let i = 0; i < index; i++) {
          node = node.next;
        }
        return node.val;
      }

      addAtIndex(index, val) {
        if (index < 0 || index > this.size) {
          return;
        }
        if (index === 0) {
          this.addAtHead(val);
        } else if (index === this.size) {
          this.addAtTail(val);
        } else {
          let node = new ListNode(val);
          let prev = null;
          let curr = this.head;
          for (let i = 0; i < index; i++) {
            prev = curr;
            curr = curr.next;
          }
          prev.next = node;
          node.next = curr;
          this.size++;
        }
      }

      deleteAtIndex(index) {
        if (index < 0 || index >= this.size) {
          return;
        }
        if (index === 0) {
          this.head = this.head.next;
          if (!this.head) {
            this.tail = null;
          }
        } else {
          let prev = null;
          let curr = this.head;
          for (let i = 0; i < index; i++) {
            prev = curr;
            curr = curr.next;
          }
          prev.next = curr.next;
          if (!prev.next) {
            this.tail = prev;
          }
        }
        this.size--;
      }
    }

    let list = new LinkedList();
    list.addAtHead(1);
    list.addAtTail(3);
    list.addAtIndex(1, 2);
    console.log(list.get(1)); // 输出2
    list.deleteAtIndex(1);
    console.log(list.get(1)); // 输出3
  </script>
</body>

</html>